package jbase.project.system.io;

import java.io.InputStream;
import java.io.OutputStream;

import jbase.project.system.core.common.EventHook;

public class IOTransfer implements Runnable {

	private volatile int status = 0x1;

	private InputStream inputStream;
	private OutputStream outputStream;
	private EventHook hook;

	public IOTransfer(EventHook hook, InputStream in, OutputStream out) {
		this.hook = hook;
		this.inputStream = in;
		this.outputStream = out;
	}

	public void stop() {
		this.status = 0x2;
	}

	@Override
	public void run() {
		try {
			int readCnt = 0;
			byte[] buff = new byte[1024];
			hook.event("io.enter");
			while (status == 0x1 && (readCnt = this.inputStream.read(buff)) != -1) {
				this.outputStream.write(buff, 0, readCnt);
				this.outputStream.flush();
			}
			hook.event("io.exit");
		} catch (Exception e) {
			hook.event("io.exception", e);
		} finally {
			try {
				this.inputStream.close();
			} catch (Exception e) {
				hook.event("warn", e.getMessage());
			}
			try {
				this.outputStream.close();
			} catch (Exception e) {
				hook.event("warn", e.getMessage());
			}
		}
	}

	public Thread createThread() {
		Thread t = new Thread(this);
		return t;
	}

	public Thread createAndStart() {
		Thread t = createThread();
		t.start();
		return t;
	}

}
